/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.application.dict;

import com.lap.auth.application.dict.assembler.DictTypeAssembler;
import com.lap.auth.application.dict.command.CreateDictTypeCmd;
import com.lap.auth.application.dict.command.UpdateDictTypeCmd;
import com.lap.auth.application.dict.dto.DictTypeDto;
import com.lap.auth.application.dict.dto.QueryDictTypePageQuery;
import com.lap.auth.application.dict.repository.DictTypeQueryRepository;
import com.lap.auth.domain.dict.DictType;
import com.lap.auth.domain.dict.repository.DictRepository;
import com.lap.auth.domain.dict.repository.DictTypeRepository;
import com.lap.auth.domain.dict.service.DictTypeValidator;
import com.lap.framework.common.dto.page.PageResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数字字典分类应用服务层
 *
 * <ol>
 *   <li>不做业务规则，只做技术规则（加密/解密是技术实现，业务不关注）
 *   <li>取数，赋值，对象转换在这层执行
 *   <li>命名有规范，动词+领域名字
 *   <li>如查询比较多，建议分开领域QueryAppService,如:分页查询，分页查询返回关联字段
 * </ol>
 */
@RequiredArgsConstructor
@Service
public class DictTypeAppService {

  private final DictTypeAssembler dictTypeAssembler;
  private final DictTypeValidator dictTypeValidator;
  private final DictTypeRepository dictTypeRepository;
  private final DictRepository dictRepository;
  private final DictTypeQueryRepository queryRepository;

  public PageResponse<DictTypeDto> queryDictTypesByPage(QueryDictTypePageQuery query) {
    return queryRepository.findByConditionPaged(query);
  }

  @Transactional(rollbackFor = Exception.class)
  public Integer createDictType(CreateDictTypeCmd cmd) {
    dictTypeValidator.validateCodeUnique(cmd.getCode());

    DictType dictType = dictTypeAssembler.toDomain(cmd);
    if (!dictType.getDictList().isEmpty()) {
      dictRepository.saveAll(dictType.getDictList());
    }
    return dictTypeRepository.save(dictType);
  }

  public Integer updateDictType(Integer id, UpdateDictTypeCmd cmd) {
    DictType dictType = dictTypeValidator.assertDictTypeExists(id);
    dictType.changeInfo(cmd.getModule(), cmd.getName(), cmd.getRemark());
    return dictTypeRepository.save(dictType);
  }

  @Transactional(rollbackFor = Exception.class)
  public Integer deleteDictType(Integer id) {
    DictType dictType = dictTypeValidator.assertDictTypeExists(id);
    dictRepository.deleteByDictTypeCode(dictType.getCode());
    return dictTypeRepository.deleteById(id);
  }
}
